require( '$d/css/common.less' );
require( './style.less' );

define([
    'require',
    'jquery',
    'header',
    'nav',
    'api',
    'combiner',
    'usergroup_manage',
    'message',
    'artCategoryHandle',
    'constants',
    'pagination',
    'bootstrap',
    './picture',
    'bigwe_component',
], function(require, $) {
    var content = $('.main_left');

    var InterFace = require('api'),
        groupManage = require('usergroup_manage'),
        ShowTitleMessage = require('message'),
        category = require('artCategoryHandle'),
        constants = require('constants'),
        picture_fn = require('./picture'),
        bc = require('bigwe_component');
    var groupManageConfig = [{
        requestType: 'post',
        groupType: 'collectArt',
        addNewUrl: InterFace.MYCOLLECTION.ADD_GROUP,
        addParamName: 'cgn', // 添加分组的参数名
        deleteUrl: InterFace.MYCOLLECTION.DEL_GROUP,
        deleteParamName: 'cgid', // 删除分组的参数名
        modifyUrl: InterFace.MYCOLLECTION.EDIT_GROUP,
        modifyParam: { // 修改分组的参数名
            groupId: 'cgid',
            groupName: 'cgn'
        },
        userGroupData: null, // 未加载请定义成null 加载完成如果没有数据赋值成空数组
        deleteCallback: function(data, deleteID) {
            var del_tag = $("#article > .article-tag > div").find('span[cgid="' + deleteID + '"]');
            if (deleteID && del_tag.hasClass('green')) {
                delete param.data.cgid;
                param.page = true;
                param.data.p = 1;
                myAjax(param);
            }
            del_tag.remove();
        },
        addCallback: function(data) {
            if (typeof data === 'string') data = $.parseJSON(data);
            var tag_cont = $("#article > .article-tag > div");
            tag_cont.append("<span cgid='" + data.id + "'>" + data.name + "</span>");
        },
        modifyCallback: function(data) {
            if (typeof data === 'string') data = $.parseJSON(data);
            group_list(this.userGroupData);
        }
    }, {
        requestType: 'post',
        groupType: 'collectImg',
        addNewUrl: InterFace.MYCOLLECTION.IMG_ADD_GROUP,
        addParamName: 'cgn', // 添加分组的参数名
        deleteUrl: InterFace.MYCOLLECTION.IMG_DELETE_GROUP,
        deleteParamName: 'cgid', // 删除分组的参数名
        modifyUrl: InterFace.MYCOLLECTION.IMG_ADD_GROUP,
        dataUnit: '张',
        modifyParam: { // 修改分组的参数名
            groupId: 'cgid',
            groupName: 'cgn'
        },
        userGroupData: null, // 未加载请定义成null 加载完成如果没有数据赋值成空数组
        deleteCallback: function(data, deleteID) {
            if (deleteID && ($(".tool_s").find('span[data-cgid="' + deleteID + '"]').hasClass('green') || $('select.group_more').val() == deleteID)) {
                $('.group_list > span').eq(0).trigger('click')
            }else {
                img_group_id = $('.group_list').find('span.green').data('cgid') || $('select.group_more').val();
            }
            img_group_list(this.userGroupData);
        },
        addCallback: function(data) {
            if (img_cd) {
                img_cd = false;
                picture_fn.init(data.id);
            }
            img_group_id = $('.group_list').find('span.green').data('cgid') || $('select.group_more').val();
            img_group_list(this.userGroupData);
        },
        modifyCallback: function(data) {
            img_group_id = $('.group_list').find('span.green').data('cgid') || $('select.group_more').val();
            img_group_list(this.userGroupData);
        }
    }];

    var img_group_id;

    groupManage.init(groupManageConfig);

    function group_list(data, deleteID) {
        var tag_cont = $("#article > .article-tag > div");
        if (data.ret == 0) {
            var group = data.data;
        } else {
            var group = data;
        }
        groupManageConfig[0].userGroupData = group;
        var html = '<span class="green">全部</span>';
        for (key in group) {
            html += "<span cgid='" + group[key].id + "'>" + group[key].group_name + "</span>";
        }

        var cgid = tag_cont.find('span.green').attr('cgid');
        $('[cgid="' + cgid + '"]', tag_cont.html(html)).addClass('green').siblings().removeClass('green');
    };

    function img_group_list(data) {
        var data = typeof data === 'string' ? $.parseJSON(data) : data;
        var grouping;
        if (data.ret == 0) {
            grouping = data.data;
        } else {
            grouping = data;
        }
        groupManageConfig[1].userGroupData = grouping;
        picture_fn.init(grouping);
        $(".article_grouping > div.group_list > span").not(':first').remove();
        $(".group_more > option").not(':first').remove();
        $("select.group_more").addClass('hide');
        var group_html = '',
            more_html = '';
        if (grouping.length > 0) {
            for (var i in grouping) {
                if (i < 4) {
                    group_html += '<span data-cgid="' + grouping[i].id + '"'+((img_group_id == grouping[i].id) ? ' class="green"' : '') +'>' + grouping[i].group_name + '</span>';
                } else {
                    more_html += '<option value="' + grouping[i].id + '"'+((img_group_id == grouping[i].id) ? ' selected = "selected"' : '') +'>' + grouping[i].group_name + '</option>';
                }
            }
        }

        if (grouping.length > 4) {
            $(".group_more").removeClass('hide');
        }

        $(".article_grouping > div.group_list").append(group_html);
        $("select.group_more").append(more_html);
        $('select.group_more').selectpicker('refresh');
    }

    var param_art = {
            url: InterFace.MYCOLLECTION.COLLECT_ART_LS,
            data: {
                rt: 'collectArt',
                p: 1,
            },
            callBack: art_list,
            page: true,
        },
        group_art = {
            url: InterFace.COMMON.GET_MEDIA,
            data: {
                rt: 'collectArt'
            },
            callBack: group_list,
        },
        img_group = {
            url: InterFace.MYCOLLECTION.GET_GROUP,
            data: {
                rt: 'collectImg'
            },
            callBack: img_group_list,
        };
    var myAjax = function(options) {
        var defaults = {
            type: 'post', //请求的方法,默认为post
            beforefn: ShowTitleMessage.show('正在加载...'),
        };

        var opt = $.extend({}, defaults, options);

        $.ajax({
            type: opt.type,
            url: opt.url || '',
            data: opt.data || '',
            dataType: opt.dataType || 'json',
            before: function() {
                opt.beforefn || '';
            },
            success: function(data) {
                var data = (typeof data === 'string') ? $.parseJSON(data) : data;
                if ($.isFunction(opt.callBack)) {
                    opt.callBack(data);
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                console.log(textStatus);
                console.log(XMLHttpRequest.status);
                console.log(XMLHttpRequest.readyState);
            },
        })
    };

    function art_list(data) {
        var arts_html = '';
        data.total = data.total || '0';
        if (param_art.page) {
            paging(data.total);
        }
        if (data.ret == '70006') {
            arts_html = '<p><span class="glyphicon glyphicon-flash"></span>文章' + data.msg + '</p>';
        } else {
            for (var i in data.data) {
                var art = data.data[i];
                var source_icon = '';

                if (art.source == 'bigwe.com') {
                    source_icon = 'icon-iconbigwe'
                } else if (art.source == 'toutiao.com') {
                    source_icon = 'icon-icontoutiao'
                } else if (art.source == 'news.163.com') {
                    source_icon = 'icon-wangyi'
                } else if (art.source == 'news.sina.com.cn') {
                    source_icon = 'icon-xinlang'
                } else if (art.source == 'ifeng.com') {
                    source_icon = 'icon-ifeng'
                } else if (art.source == 'mp.weixin.qq.com') {
                    source_icon = 'icon-weixin'
                }

                var cs = art.copyright_stat * 1; //原创标识

                var copyright_img = '';
                if (cs == 1 || cs == 2) {
                    if (art.source == 'toutiao.com') {
                        copyright_img = '<span class="toutiao_copyright">原创</span>';
                    }
                    if (art.source == 'bigwe.com') {
                        copyright_img = '<img src="' + constants.resPath + '/images/original1.png" alt="" class="original"/>';
                    }
                    if (art.source == 'mp.weixin.qq.com') {
                        copyright_img = '<img src="' + constants.resPath + '/images/original2.png" alt="" class="original"/>';
                    }
                }
                var time = (new Date(art.publish_time_millis * 1)).format('yyyy-MM-dd hh:mm');
                if (art.publish_time_millis == null) {
                    time = art.create_time.substr(0, 16)
                }

                var img_url = '/timthumb.php?w=130&src=' + art.cover_img_url;

                arts_html += '<div class="article-sub">' +
                    ' <div class="article-title"><input type="checkbox" data_cd="' + art.cd + '"><span style="background:' + category.category_color[category.getBWCode(art.category_code).code] + '">' + category.getBWCode(art.category_code).name + '</span><a href="/article/index/p/' + art.cd + '" target="_blank">' + art.title + '</a></div>' +
                    '<p>&nbsp;</p>';
                if (art.cover_img_url) {
                    arts_html += '<div class="cover_photo">' +
                        '<a href="/article/index/p/' + art.cd + '" target="_blank"><img src="' + img_url + '" alt="" onerror="this.src=\'' + constants.resPath + '/images/wuyulantu2.png\';"></a>' + copyright_img +
                        '</div>'
                }
                arts_html += '<div class="article-sub-taxt ' + ((art.cover_img_url) ? 'article_sub_rq' : 'article_sub_rq_fluid') + '" data-articleid="' + art.cd + '" data-id="' + art.cd + '" data-title="' + art.title + '" data-img="' + img_url + '" data-url="/article/index/p/' + art.cd + '">' +
                    '<p>' + (art.summary || "") + '</p>' +
                    '<span class="iconfont platform-icon ' + source_icon + '"></span>' +
                    '<span class="article-account">' + (art.publisher || art.author || '') + '</span>' +
                    '<span class="article-time">' + time + '</span>' +
                    '<span class="glyphicon glyphicon-trash icon-delete article-collect" data-toggle="tooltip" title="取消收藏"></span>' +
                    '<span class="iconfont article-merge icon-box" style="font-size: 18px;" addcar-event data-toggle="tooltip" title="加入合成器"></span>' +
                    '<span class="iconfont mobile_packet icon-huhuan"  data-toggle="tooltip" title="移动分组"></span>' +
                    '</div></div>';
            }
        }

        $('#article .total_number').text(data.total);
        $('.nav_box > li').eq(0).find('span').text(data.total);
        $('#article > .content_list').empty().append(arts_html);
        $('[data-toggle="tooltip"]').tooltip({
            trigger: 'hover'
        });

        if (!$("#article .batch-selection").is(':hidden')) {
            $("#article .batch-selection input").attr("checked", false);
            $('#article > .content_list .article-title > input').show();
            $('#article .bat_check').text('无');
        }
        ShowTitleMessage.hide();
    };

    function paging(number) {
        if (number > 10) {
            $('#article > .paging').show();
        } else {
            $('#article > .paging').hide();
        };
        if (param_art.data.p != 1) {
            var current_page = param_art.data.p - 1;
        }
        $('#article > .paging').pagination(number, {
            num_edge_entries: 2,
            items_per_page: 10,
            current_page: current_page,
            prev_text: '上一页',
            next_text: '下一页',
            callback: function(page_index, jq) {
                if (param_art.page) {
                    param_art.page = false;
                    return;
                } else {
                    param_art.data.p = page_index + 1;
                    myAjax(param_art);
                }
            }
        });
    };
    myAjax(param_art);
    myAjax(group_art);

    /*分组切换*/
    $(".article-tag > div").on("click", "span", function() {
        if ($(this).hasClass("green")) {
            return;
        }
        $(this).addClass("green").siblings().removeClass("green");

        var cgid = $(this).attr('cgid');
        param_art.page = true;
        param_art.data.p = 1;
        param_art.data.cgid = cgid;
        myAjax(param_art);
        $(".batch-selection input[type='checkbox']")[0].indeterminate = false;
        $(".batch-selection input[type='checkbox']").removeAttr('checked');
        $('.bat_check').text('无');
    });

    /*
     * ========== * 筛选 * ==========
     */
    var filter_selection = content.find('.filter_selection');
    filter_selection.on('click', '.filter-btn', function() {
        $('.selectpicker').selectpicker();
        var $this = $(this),
            _t = $this.data('show');
        if (_t) {
            $this.siblings(".filter-select").hide();
            $this.find("span:last-child").text("展开筛选");
            $this.find("span:first-child").addClass("glyphicon-filter").removeClass("glyphicon-menu-up");
            $this.attr('data-show', false).data('show', false);
        } else {
            $this.siblings(".filter-select").show();
            $this.find("span:first-child").removeClass("glyphicon-filter").addClass("glyphicon-menu-up");
            $this.find("span:last-child").text("收起筛选");
            $this.attr('data-show', true).data('show', true);
        }
    });

    filter_selection.on('change', 'select', function() {
        var val = $(this).val();
        var name = $(this).attr('name');

        param_art.data.p = 1;
        param_art.data[name] = val;
        param_art.page = true;
        myAjax(param_art);
    });

    /*移动分组*/
    $(".content_list").on("click", ".mobile_packet", groupmove);
    $(document).on('click', '.art_group .category', cg);
    /*批量移动分组*/
    $(".batch-grouping").click(groupmove);

    function groupmove(e) {
        var obj = event.srcElement.type;
        e = e || event;
        e.stopPropagation();

        var groupsHtml = '';
        var groupData = groupManageConfig[0].userGroupData;

        if (!groupData.length) {
            ShowTitleMessage.showWarning('您还没有分组或者该图文已存在您唯一分组中', 1500);
            return;
        }

        if (obj == 'button') {
            var num = "";
            $(this).parent().siblings('.content_list').find(':checkbox').each(function() {
                if (this.checked) {
                    if (num.length > 1) {
                        num += ",";
                    }
                    num += $(this).attr("data_cd");
                }
            });
            groupsHtml += '<div article_group="' + num + '" class="category-tab art_group" style="display: block;" name="all">';
        } else {
            groupsHtml += '<div article_group="' + $(this).parent().attr('data-articleid') + '" class="category-tab art_group" style="display: block;">';
        }

        var thisGroupId = $(this).attr('group_id');

        for (i in groupData) {
            if (groupData[i].id * 1 == thisGroupId * 1) continue;
            if (i == 0) {
                groupsHtml += '<div class="category" target_group="' + groupData[i].id + '"><div class="arrow"></div>' + groupData[i].group_name + '</div>';
            } else {
                groupsHtml += '<div class="category" target_group="' + groupData[i].id + '">' + groupData[i].group_name + '</div>';
            }
        }
        groupsHtml += '</div>';

        var left = 0,
            top = 0;

        var thisHeight = $(this).outerHeight(),
            thisWidth = $(this).outerWidth(),
            thisTop = $(this).offset().top,
            thisLeft = $(this).offset().left;
        if (obj == 'button') {
            left = thisLeft + thisWidth - thisWidth / 2 + 55;
            top = thisTop + thisHeight - thisHeight / 2 - 15;
        } else {
            left = thisLeft + thisWidth - thisWidth / 2 + 25;
            top = thisTop + thisHeight - thisHeight / 2 - 15;
        }

        $('.art_group').remove();
        $('body').append($(groupsHtml).css({
            left: left,
            top: top
        }));

        $(document).bind('click.category', function() {
            $('.art_group').remove();
            $(document).unbind('click.category');
            $('.picture_details_show').removeClass('picture_details_show');
        });
    }

    function cg() {
        var id = $(this).parent().attr('article_group'),
            cgid = $(this).attr('target_group'),
            name = $(this).parent().attr('name');

        var cont_wrap;

        cont_wrap = $('#article');
        if (cont_wrap.find(".article-tag > div > span.green").index() != 0) {
            if (name) {
                cont_wrap.find(".content_list :checkbox").each(function() {
                    if (this.checked) {
                        $(this).parents('.article-sub').remove();
                    };
                });
            } else {
                cont_wrap.find('[data-articleid="' + id + '"]').parent().remove();
            }
        }
        if (name) {
            cont_wrap.find(".batch-selection input[type='checkbox']")[0].indeterminate = false;
            cont_wrap.find(".batch-selection input[type='checkbox']").removeAttr('checked');
            cont_wrap.find('.content_list input[type="checkbox"]').removeAttr('checked');
            cont_wrap.find('.batch-selection > button').prop('disabled', true);
            cont_wrap.find('.bat_check').text('无');
        }
        $.post('/my_assets/cg', {
            rt: 'collectArt',
            cgid: cgid,
            cd: id
        }, function(data) {
            var data = typeof data === 'string' ? $.parseJSON(data) : data;
            if (data.ret == 0) {
                myAjax(art_mobile_packet);
                ShowTitleMessage.show('操作成功！', 1500);

                if (cont_wrap.find(".article-tag > div > span.green").index() != 0) {
                    if (!cont_wrap.find('.paging').is(':hidden') && cont_wrap.find('.article-sub-taxt').length == 0) {
                        param.page = true;
                        (param.data.p > 1) ? (param.data.p -= 1) : (param.data.p);
                    }
                    myAjax(param);
                }
            } else {
                ShowTitleMessage.showWarning(data.msg, 1500);
            }
        });
    };

    /*批量管理*/
    $(".batch").click(function() {
        var _this = $(this);
        var _parents = _this.parents('.tab-pane');
        if (_this.hasClass('manage')) {
            _this.text("批量管理");
            _parents.find(".batch-selection").hide();
            _parents.find(".content_list input").hide();
            _this.removeClass("manage");
            _parents.find('input[type="checkbox"]').removeAttr('checked');
            _parents.find(".batch-selection input[type='checkbox']")[0].indeterminate = false;
            _parents.find('.batch-selection > button').prop('disabled', true);
            _parents.find(".filter_selection").show();
        } else {
            _this.text("退出管理");
            _parents.find(".batch-selection").show();
            _parents.find(".content_list input").show();
            _this.addClass("manage");
            _parents.find(".filter_selection").hide();
        }
    });
    /*全选*/
    $(".batch-selection > label :checkbox").change(check_change);
    $(".content_list").on("change", "input[type='checkbox']", check_change);

    /*单选全选*/
    function check_change() {
        var _this = $(this);
        var _parents = _this.parents('.tab-pane');
        if (_this.attr('name') == 'all') {
            if (_this[0].checked) {
                _parents.find(":checkbox").prop('checked', true);
                _parents.find('.batch-selection > button').removeAttr('disabled');
                _parents.find('.bat_check').text(_parents.find('.content_list :checked').length + '篇');
            } else {
                _parents.find('.content_list input[type="checkbox"]').removeAttr('checked');
                _parents.find('.batch-selection > button').prop('disabled', true);
                _parents.find('.bat_check').text('无');
            }
        } else {
            var graphLen = _parents.find('.content_list input[type="checkbox"]').length,
                checkLen = _parents.find('.content_list :checked').length;
            var $checkAll = _parents.find(".batch-selection input[type='checkbox']");
            if (checkLen == 0) {
                $checkAll[0].indeterminate = false;
                $checkAll.removeAttr('checked');
                _parents.find('.batch-selection > button').prop('disabled', true);
                _parents.find('.bat_check').text('无');
            } else {
                _parents.find('.batch-selection > button').removeAttr('disabled');
                _parents.find('.bat_check').text(checkLen + '篇');
                if (graphLen != checkLen) {
                    $checkAll[0].indeterminate = true;
                } else {
                    $checkAll.prop('checked', 'checked');
                    $checkAll[0].indeterminate = false;
                }
            }
        }
    };
    /*分组文章数同步*/
    var art_mobile_packet = {
        url: InterFace.COMMON.GET_MEDIA,
        data: {
            'rt': 'collectArt'
        },
        callBack: group_id,
    };

    function group_id(data) {
        var data = typeof data === 'string' ? $.parseJSON(data) : data;

        if (data.ret == '0') {
            var arts = data.data;
            for (i in arts) {
                $('[groupid=\"' + arts[i].id + '\"]').find('.battery-number').text(arts[i].group_num);
            }
        } else {
            ShowTitleMessage.showWarning(data.msg, 2000);
        }
        return;
    };

    /*删除素材*/
    $(".content_list").on("click", ".article-collect", function() {
        var _this = $(this);
        var target_id = $(this).parent().attr("data-articleid");

        bc.deleteConfirmShowBottom({
            obj: this,
            text: '确认要取消收藏吗？',
            fun: function() {
                _this.parents(".article-sub").remove();
                deletedata(target_id);
            }
        });
    });

    /*批量删除*/
    $(".batch-del").click(function() {
        var cont_wrap = $(this).parent().siblings('.content_list');
        var object = "";
        bc.deleteConfirmShowBottom({
            obj: this,
            text: '确认要取消收藏吗？',
            fun: function() {
                cont_wrap.find("input").each(function() {
                    if (this.checked) {
                        $(this).parents(".article-sub").remove();
                        if (object.length > 1) {
                            object += ",";
                        }
                        object += $(this).attr("data_cd");
                    }
                });
                $(this).parent().find("input[type='checkbox']")[0].indeterminate = false;
                $(this).parent().find("input").removeAttr('checked');
                $(this).parent().find(".bat_check").text('无');
                deletedata(object);
            }
        });
    });

    function deletedata(targetid) {
        var del_art = {
            url: InterFace.MYCOLLECTION.FAVORITES_DEL,
            data: {
                id: targetid,
                rt: 'collectArt'
            },
            callBack: del_sx,
        };
        myAjax(del_art);
    };

    function del_sx(data) {
        if ($('#article > .content_list > div').length == 0) {
            param_art.page = true;
            if (param_art.data.p != 1) {
                param_art.data.p -= 1;
            }
        }
        myAjax(param_art);
        ShowTitleMessage.show('取消收藏成功！', ShowTitleMessage.showTime);
        $('.batch-selection > button').prop('disabled', true);
    }

    /*文章、图片切换*/
    var input_Record = {
        art: '',
        img: '',
    };
    $(".nav_box").lavalamp({
        fx: "backout",
        speed: 700,
        click: function(event, menuItem) {
            var i = $(menuItem).index();
            var search_input = $('.search_input');
            $('.tab-content > div').removeClass('in active');
            $('.tab-content > div').eq(i).addClass('in active');

            if (i == 1 && !$(".nav_box > li").eq(1).data('list')) {
                $(".nav_box > li").eq(1).data('list', true);
                picture_fn.init();
                myAjax(img_group);
            }
            if (i == 0) {
                input_Record.img = search_input.val();
                search_input.val(input_Record.art);
                $('.picture_batch').addClass('hide');
                if ($('.search').is(':hidden')) {
                    $('.search').removeClass('hide');
                }
            } else {
                input_Record.art = search_input.val();
                search_input.val(input_Record.img);
                $('.picture_batch').removeClass('hide');
                if ($('.picture_batch').data('manager')) {
                    $('.search').addClass('hide');
                }
            }
        }
    });


    /*搜索*/
    $(".search_btn").click(function() {
        var value = $("#search_text").val();
        var i = $('.nav_box > li.current').index();
        switch (i) {
            case 0:
                param.page = true;
                param.data.p = 1;
                param.data.key = value;
                myAjax(param);
                break;
        }
    });

    var img_cd = false;

    $(document).on('click', '.add_grouping > .sure', function() {
        var _group = $('.sure_val').val();
        if (_group) {
            $(this).parent().remove();
            img_cd = true;
            groupManage.commonAddGroup(_group,1);
        } else {
            message.show('请输入分组名', 1500);
            $('.sure_val').focus();
        }
    });
});
